package common;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.Spanned;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


/**
 * Depiction: view快速绑定工具
 * <p>
 * Modify:
 * <p>
 * Author: Kevin Lynn
 * <p>
 * Create Date：2016年2月19日 下午4:52:24
 * <p>
 * 
 * @version 1.0
 * @since 1.0
 */
public class ViewHandler {
	
	private View			  mConvertView;
	private Activity		  mActivity;
	private SparseArray<View> mViewArray;  // 包含了View引用的SparseArray
							  
	public ViewHandler(View convertView) {
		this.mConvertView = convertView;
	}
	
	public ViewHandler(Activity activity) {
		this.mActivity = activity;
	}
	
	@SuppressWarnings ("unchecked")
	public <T extends View> T get(int viewId) {//通过ViewId得到View
		
		if (mActivity == null) {
			// 从指定父view里找到child view
			SparseArray<View> viewHolder = (SparseArray<View>) mConvertView.getTag();
			if (viewHolder == null) {
				viewHolder = new SparseArray<View>();
				mConvertView.setTag(viewHolder);
			}
			
			View childView = viewHolder.get(viewId);
			if (childView == null) {
				childView = mConvertView.findViewById(viewId);
				viewHolder.put(viewId, childView);
			}
			return (T) childView;
			
		} else {
			// 从指定Activity里找到child view
			if (mViewArray == null) {
				mViewArray = new SparseArray<View>();
			}
			
			View childView = mViewArray.get(viewId);
			if (childView == null) {
				childView = mActivity.findViewById(viewId);
				mViewArray.put(viewId, childView);
			}
			return (T) childView;
		}
	}
	
	public void setText(int viewId, String text) {// 通过ViewId设置Text
		((TextView) get(viewId)).setText(text);
	}
	
	public void setText(int viewId, Spanned text) {// 通过ViewId设置Text
		((TextView) get(viewId)).setText(text);
	}
	
	public void setTextColor(int viewId, int color) {//通过ViewId设置TextColor
		((TextView) get(viewId)).setTextColor(color);
	}
	
	public void setImageResource(int viewId, int resId) {//通过ViewId设置图片
		((ImageView) get(viewId)).setImageResource(resId);
	}
	
	public void setImageBitmap(int viewId, Bitmap bm) {// 通过ViewId设置图片
		((ImageView) get(viewId)).setImageBitmap(bm);
	}
	
	public void setImageDrawable(int viewId, Drawable drawable) {//通过ViewId设置图片
		((ImageView) get(viewId)).setImageDrawable(drawable);
	}
	
	public void setImageUrl(int id, String url) {//通过ViewId设置网络图片
		//        Rosemary.loadImage(url, (ImageView) get(id));
	}
	
	public void setImageUrl(int id, String url, int resId) {// 通过ViewId设置网络图片
		//        Rosemary.loadImage(url, (ImageView) get(id), resId);
	}
	
	public void setVisibility(int viewId, int visibility) {//通过ViewId设置隐藏和显示
		get(viewId).setVisibility(visibility);
	}
	
	public void setOnClickListener(int viewId, View.OnClickListener l) {//通过ViewId设置点击监听
		get(viewId).setOnClickListener(l);
	}
}
